import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from HTMLTestRunnerCN import HTMLTestReportCN
import time

# 定义文件目录
def make_report():
    """生成测试报告"""
    now = time.strftime('%Y-%m-%d %H_%M_%S') # 获取当前时间戳并整理格式
    filename = r'./test_report/' + now + 'result.html' # 文件的命令以及打开路径
    with open(filename, 'wb') as fr:
        runner = HTMLTestReportCN(stream=fr, title="测试报告", description="详情")
        # 下方的suite需要从testsuite文件夹里面导入测试套件
        runner.run(suite())

def new_report(testreport):
    """从测试报告文件夹中取出最新的测试报告"""
    dir_list = os.listdir(testreport)
    dir_list.sort(key=lambda fn: os.path.getmtime(testreport + r"/" + fn))
    file_new = os.path.join(testreport, dir_list[-1])
    return file_new

def send_mail(for_out_file, smtp_server, username, pwd, receiver):
    with open(for_out_file, 'rb') as f:
        mail_body = f.read()
    subject = '接口自动化测试报告'
    msg_text = MIMEMultipart()
    msg_text['Subject'] = Header(subject, 'utf-8')

    msg = MIMEText(mail_body, 'base64', 'utf-8')
    msg["Content-Type"] = 'application/octet-stream'
    msg["Content-Disposition"] = 'attachment; filename="test_result.html"'

    msg_text.attach(msg)
    smtp_obj = smtplib.SMTP(smtp_server, 25)
    smtp_obj.login(username, pwd)
    smtp_obj.sendmail(username, receiver, msg_text.as_string())
    smtp_obj.quit()

if __name__ == '__main__':

    smtp_ser = 'smtp.qq.com'
    user = 'xxxxxx@qq.com'
    receivers = ['xxxxxx@163.com']
    password = 'xxxxxx'
    result_dir = r'./test_report'
    out_file = new_report(result_dir)

    make_report()
    new_report(result_dir)
    send_mail(out_file, smtp_ser, user, password, receivers)
